package me.jiatao.paging3.network.viewmodel

import android.app.Application
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import kotlinx.coroutines.CancellationException
import me.jiatao.paging3.network.retrofit.HttpConst
import me.jiatao.paging3.network.retrofit.HttpResult
import me.jiatao.paging3.network.retrofit.apiCall

/**
 * 封装网络请求的ViewModel
 * 用于网略错误时，异常信息提示等
 */
open class HttpViewModel(application: Application) : AndroidViewModel(application) {

    /**
     * 执行网络访问并获取数据结果
     */
    suspend fun <T> execHttpResponse(httpHandler: suspend () -> HttpResult<T>): T {
        val httpResult = apiCall {
            httpHandler()
        }

        //错误信息
        val cancelMsg: String
        //返回状态码错误
        if (httpResult.code != HttpConst.CODE_SUCCESS) {
            cancelMsg = httpResult.message ?: "请求错误,请稍后重试"
        }
        //获取数据为空
        else if (httpResult.data == null) {
            cancelMsg = "获取数据为空"
        }
        //返回数据
        else {
            return httpResult.data!!
        }

        println(cancelMsg)
        Toast.makeText(getApplication(), cancelMsg, Toast.LENGTH_LONG).show()
        throw CancellationException()
    }

    /**
     * 获取状态码
     */
    suspend fun <T> execHttpStatus(httpHandler: suspend () -> HttpResult<T>): Boolean {
        val httpResult = apiCall {
            httpHandler()
        }

        //返回状态码
        if (httpResult.code == HttpConst.CODE_SUCCESS) {
            return true
        } else {
            val cancelMsg = httpResult.message ?: "请求错误,请稍后重试"
            println(cancelMsg)
            Toast.makeText(getApplication(), cancelMsg, Toast.LENGTH_LONG).show()
            throw CancellationException()
        }
    }
}